import {
  Http
} from '../../utils/http'
import {
  Tv
} from '../../model/Tv'
import {
  config
} from "../../config/config"
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';


Page({

  data: {
    tvId: '',
    tvName: undefined,
    videoUrl: [],
    result: [],
    show: true,
    tvList: [],
    videoHttp: '',
    series_no: undefined,
    videoList_show: false,
    series_no: '',
    uploadFileHttps:config.apiBaseUrl+'wechat/attachment/upload'
  },

  //生命周期函数--监听页面加载
  onLoad: async function (options) {
    this.setData({
      tvId: options.tvListId,
      videoHttp: config.apiBaseUrl,
    })

    let http = await Http.login();

    if (Object.prototype.toString.call(options.scene) !== '[object Undefined]') { //空
      this.setData({
        series_no: options.scene
      })
    }

    this.bind();
  },

  //生命周期函数--监听页面显示
  onShow: async function () {
    if (this.data.tvId == undefined) {
      console.log('tvId为undified');
      this.setData({
        videoList_show: true
      })
    } else {
      let tv = await Tv.get_tvbox_detail(this.data.tvId);
      this.getTvDetail(tv)
      this.setData({
        videoList_show: false
      })
    }
  },

  //判断设备号是否绑定过
  bind: async function () {
    let tv = await Tv.is_bind_series_no(this.data.series_no);
    if (tv.code == 0) {
      if (tv.data.flag == 1) {
        setTimeout(() => {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/video_home/index',
            })
          }, 3000);
          wx.showToast({
            title: tv.msg,
            icon:'error'
          })
        }, 3000);
      }
    } else {
      console.log(tv.data.msg);
    }
  },

  //获取到视频组
  getTvDetail(tv) {
    if (tv.code == 0) {
      this.setData({
        series_no: tv.data.series_no,
        videoUrl: tv.data.video_files.split(','),
        tvName: tv.data.name
      })
      console.log('获取TVBox详情' + tv.msg);
    } else {
      console.log('获取TVBox详情' + tv.msg);
    }
  },

  //点击添加视频按钮
  addVideoTap: function () {

    var that = this;
    //选择视频
    wx.chooseVideo({
      sourceType: ['album', 'camera'], //视频选择的来源
      maxDuration: 15, //拍摄视频最长拍摄时间，单位秒
      camera: 'back', //默认拉起的是前置或者后置摄像头。部分 Android 手机下由于系统 ROM 不支持无法生效
      success(res) {
        wx.showLoading({
          title: '加载中...',
          icon: 'loading',
        });

        let http = Http.login()
        //上传视频
        wx.uploadFile({
          url: that.data.uploadFileHttps, //开发者服务器的 url
          filePath: res.tempFilePath, //要上传文件资源的路径 String类型！！！
          name: 'file', //文件对应的 key ,(后台接口规定的关于图片的请求参数)
          header: {
            'content-type': 'multipart/form-data'
          }, //设置请求的 header
          formData: {

          }, //HTTP 请求中其他额外的参数
          success: function (res) {
            //上传成功后隐藏加载框
            wx.hideLoading();
            if (res != '' && res != undefined)
              var data = JSON.parse(res.data)
            if (data.code == 0) {
              var arr = that.data.videoUrl;
              arr.push([data.data.url])
              that.setData({
                videoUrl: arr
              })
            } else {
              console.log("code码为非0");
              console.log(data);
            }
          },
          fail: function (res) {
            console.log('uploadFile失败:');
            wx.showToast({
              title: '上传失败',
              icon: 'error'
            }, 500)
            console.log(res);
            wx.hideLoading();
          }
        })
      },
    })
  },

  //点击删除视频按钮
  removeVideoTap: function () {
    this.setData({
      show: !this.data.show
    })
  },

  //点击删除视频小按钮
  onChange(event) {
    this.setData({
      result: event.detail,
    });
    if (this.data.videoUrl != '') {
      for (let i = 0; i < this.data.videoUrl.length; i++) {
        if (this.data.videoUrl[i] == this.data.result[i]) {
          let a = this.data.videoUrl
          let urls = a[i]
          this.del(urls);
          a[i] = ""
          this.setData({
            videoUrl: a,
          })
        }
        for (let a = 0; a < i; a++) {
          if (this.data.videoUrl[i] == this.data.result[a]) {
            let a = this.data.videoUrl
            let urls = a[i]
            this.del(urls);
            a[i] = ""
            this.setData({
              videoUrl: a,
            })
          }
        }
      }
    } else {
      wx.showToast({
        title: '没有任何视频',
        icon: 'error'
      })
    }
    this.setData({
      result: ''
    });
  },

  //视频删除接口实现
  del: async function (urls) {
    var that = this;
    if (urls != '') {
      let tvdel = await Tv.get_del(urls);
      if (tvdel.code == 0) {
        console.log(tvdel.msg);
        for (let i = 0; i < this.data.videoUrl.length; i++) {
          if (this.data.videoUrl[i] == "") {
            let a = this.data.videoUrl
            a.splice(i, 1)
            this.setData({
              videoUrl: a
            })
          }
        }
      } else {
        console.log(tvdel.msg);
      }
    }
  },

  //点击提交按钮
  submitVideoTap: async function () {
    var that = this;
    //如果tvId为undefined则表现在为创建Tv盒子
    if (this.data.tvId == undefined) {
      if (this.data.tvName == '' || this.data.tvName == undefined) {
        wx.showToast({
          title: '名称不能为空',
          icon: 'error'
        })
      } else if (this.data.videoUrl == '' || this.data.videoUrl == undefined) {
        wx.showToast({
          title: '视频组不能为空',
          icon: 'error'
        })
      } else {
        const beforeClose = (action) => new Promise((resolve) => {
          setTimeout(() => {
            if (action === 'confirm') {
              that.saveTvbox();
              resolve(true);
              setTimeout(() => {
                function a() {
                  setTimeout(() => {
                    wx.showToast({
                      title: '增加成功',
                      icon: 'success'
                    })
                  }, 1000);
                }
                wx.navigateTo({
                  url: '/pages/video_home/index',
                })
              }, 1000);
            } else {
              // 拦截取消操作
              resolve(true);
            }
          }, 1000);
        });

        Dialog.confirm({
          title: '提交',
          message: '确认提交吗？',
          beforeClose
        });
      }
    } else {
      const beforeClose = (action) => new Promise((resolve) => {
        setTimeout(() => {
          if (action === 'confirm') {
            that.edit();
            resolve(true);
            setTimeout(() => {
              wx.showToast({
                title: '修改成功',
                icon: 'success'
              })
              that.onShow()
            }, 1000);
          } else {
            // 拦截取消操作
            resolve(true);
          }
        }, 1000);
      });

      Dialog.confirm({
        title: '提交',
        message: '确认提交吗？',
        beforeClose
      });
    }
  },

  //修改接口实现
  edit: async function () {
    //TV盒子列表 修改
    let tvListUpdate = await Tv.get_edit_tvbox_detail(this.data.tvId, this.data.tvName, this.data.videoUrl.toString(), this.data.series_no);
    if (tvListUpdate.code == 0) {
      console.log(tvListUpdate.msg);
    } else {
      console.log(tvListUpdate.msg);
    }
  },

  //Tv盒子增加接口实现
  saveTvbox: async function () {
    let saveTvbox = await Tv.save_tvbox_detail(this.data.tvName,this.data.videoUrl.toString(),this.data.series_no);
    if (saveTvbox.code == 0) {
      console.log(saveTvbox);
    } else {
      console.log(saveTvbox.msg);
    }
  }

})